// miniprogram/pages/register/register.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    openid:'',
    /**列表数据 */
    formData: {
      'gender': '0',
      'userType': '0'
    },
    /**用户类型 */
    userType:['查勘人','申请人','管理员'],
    userTypeIndex: 0,
    /**性别 */
    radioItems: [
      {name: '男', value: 0, checked: true},
      {name: '女', value: 1},
      {name: '???', value: 2}
    ],
    /**验证规则 */
    rules: [{
        name: 'username',
        rules: [{required: true, message: '用户名是必选项'}],
    }, {
        name: 'password',
        rules: [{required: true, message: '密码必填'}],
    }]

  },
  bindCountryChange: function(e) {
    this.setData({
      userTypeIndex: e.detail.value,
      [`formData.userType`]: e.detail.value
    })
  },
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value);

    var radioItems = this.data.radioItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
        radioItems[i].checked = radioItems[i].value == e.detail.value;
    }

    this.setData({
        radioItems: radioItems,
        [`formData.gender`]: e.detail.value
    });
  },

  formInputChange(e) {
    const {field} = e.currentTarget.dataset
    this.setData({
        [`formData.${field}`]: e.detail.value
    })
  },
  submitForm() {
    this.setData({
      loading: !this.data.loading
    })
    this.selectComponent('#form').validate(async (valid, errors) => {
        console.log('valid', valid, errors)
        if (!valid) {
            const firstError = Object.keys(errors)
            console.log('firstError:'+firstError)
            if (firstError.length) {
                this.setData({
                    error: errors[firstError[0]].message,
                    loading: !this.data.loading
                })

            }
        } else {
          await wx.cloud.database().collection('user').where({username: this.data.formData.username}).get().then(res=>{
            console.log('res:'+JSON.stringify(res))
            console.log('length:'+res.data.length)
            if(res.data.length != 0 ){
              this.setData({
                error: '用户名重复',
                loading: !this.data.loading
              })
            }else{
              this.setData({
                loading: !this.data.loading
              })
              wx.showToast({
                title: '校验通过'
              })
              // wx.cloud.callFunction({
              //   name: 'register',
              //   data: this.data.formData,
              //   success: res=>{
              //     wx.showToast({
              //       icon: 'none',
              //       title: '成功'
              //     })
              //     wx.navigateBack()
              //   }
              // })
            }
          })
            
        }
    })
    console.log(this.data.formData)
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        
      }
    })
    if (app.globalData.openid) {
      this.setData({
        openid: app.globalData.openid
      })
    }
    wx.setNavigationBarTitle({
      title: '注册用户'
    })
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})